package com.xbongbong.saas.model.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.xbongbong.paas.domain.entity.PaasFormExplainEntity;
import com.xbongbong.paas.model.PaasFormExplainModel;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.redis.PaasRedisHelper;
import com.xbongbong.paas.redis.RedisPrefixConstant;
import com.xbongbong.paas.redis.RedisTimeConstant;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.pro.domain.dao.ScoreRuleDao;
import com.xbongbong.pro.domain.entity.ScoreRuleEntity;
import com.xbongbong.saas.model.ScoreRuleModel;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;

/**
 * @description:  评分规则
 * @Author: chunyang.qin
 * @date: 2020-11-27 17:37
 * @since v1.0
 */
@Service("scoreRuleModel")
public class ScoreRuleModelImpl implements ScoreRuleModel {

    @Resource
    private ScoreRuleDao scoreRuleDao;
    @Resource
    private PaasRedisHelper paasRedisHelper;
    @Resource
    private PaasFormExplainModel paasFormExplainModel;

    @Override
    public Integer insert(ScoreRuleEntity entity) throws XbbException {
        long now = DateUtil.getInt();
        entity.setAddTime(now);
        entity.setUpdateTime(now);
        return scoreRuleDao.insert(entity);
    }

    @Override
    public Integer update(ScoreRuleEntity entity) throws XbbException {
        long now = DateUtil.getInt();
        entity.setUpdateTime(now);
        return scoreRuleDao.update(entity);
    }

    @Override
    public List<ScoreRuleEntity> findEntitys(Map<String, Object> param) {
        return scoreRuleDao.findEntitys(param);
    }

    @Override
    public Integer getEntitysCount(Map<String, Object> param) {
        return scoreRuleDao.getEntitysCount(param);
    }

    @Override
    public List findEntitysWithoutSub(Map<String, Object> param) {
        return null;
    }

    @Override
    public ScoreRuleEntity getByKey(Long key, String corpid) {
        return scoreRuleDao.getByKey(key,corpid);
    }

    @Override
    public ScoreRuleEntity getByFormId(Long formId, String corpid) {
        return scoreRuleDao.getByFormId(formId,corpid);
    }

    @Override
    public Integer deleteByKey(Long key, String corpid) {
        return scoreRuleDao.deleteByKey(key,corpid);
    }

    /**
     * 判断该表单下是否有启用的评分规则
     * @param corpid
     * @param formId
     * @return
     * @throws XbbException
     */
    @Override
    public Boolean haveEnabledScoreRule(String corpid, Long formId) throws XbbException {
        String value = paasRedisHelper.getValue(RedisPrefixConstant.ENABLED_SCORE_RULE_FLAG, formId.toString());

        if(StringUtil.isEmpty(value)){
            //缓存中没有，重新刷新缓存
            return setEnabledScoreRule2Redis(corpid,formId,null);
        }
        Integer flag = JSON.parseObject(value, Integer.class);
        return flag == 1;
    }

    /**
     * 把该表单下是否有启用的评分规则缓存起来,并返回结果
     * value 缓存的值,如果为null，则查询一遍数据库是否有启用的评分规则
     * @param corpid
     * @param formId
     */
    @Override
    public Boolean setEnabledScoreRule2Redis(String corpid , Long formId , Integer value) throws XbbException {
        //如果有启用的评分规则的话，那么缓存的值为1，没有就是0
        Integer redisValue = 0;
        if(Objects.isNull(value)){
            Map<String, Object> params = new HashMap<>(4);
            params.put("corpid", corpid);
            params.put("formId", formId);
            params.put("enable", 1);
            params.put("del", 0);
            List<ScoreRuleEntity> enableScoreRuleList = findEntitys(params);
            if(CollectionsUtil.isNotEmpty(enableScoreRuleList)){
                redisValue = 1;
            };
        }else{
            redisValue = value;
        }
        paasRedisHelper.setValue(RedisPrefixConstant.ENABLED_SCORE_RULE_FLAG, formId.toString(), JSON.toJSONString(redisValue.toString()),  RedisTimeConstant.LONG_DURATION);
        //根据是否有启用的评分规则，修改解释中score字段的isOpen
        PaasFormExplainEntity explainEntity = paasFormExplainModel.getByFormId(formId, corpid);
        List<FieldAttrEntity> explainList = JSONArray.parseArray(explainEntity.getExplains(), FieldAttrEntity.class);
        Optional<FieldAttrEntity> score = explainList.stream().filter(item -> Objects.equals(item.getSaasAttr(), "score")).findFirst();
        if(!Objects.equals(Optional.empty(),score)){
            FieldAttrEntity scoreField = score.get();
            //有启用的评分规则时，"评分"字段设为启用；没有则设为"不启用"
            if((redisValue == 1 && Objects.equals(scoreField.getIsOpen(),0)) ||  (redisValue == 0 && Objects.equals(scoreField.getIsOpen(),1))){
                //IsOpen和visable两个属性都改掉(只改 isOpen会导致有些地方会在 isOpen为0时，把visable也改为0)
                scoreField.setIsOpen(redisValue);
                scoreField.setVisible(redisValue);
                explainEntity.setExplains(JSON.toJSONString(explainList));
                paasFormExplainModel.update(explainEntity);
            }
        }
        return redisValue.equals(1) ;
    }
}
